package com.zbxx.action;

import com.zbxx.domain.Page;
import com.zbxx.domain.User;
import com.zbxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserAction {
    @Autowired
    private UserService userService;


    //登录验证
    @RequestMapping("/login")//
    public String login(String name, String password, HttpSession session, Model model) throws Exception {
        User user = userService.login(name, password);
        if (user == null) {
            model.addAttribute("error", "请输入正确的用户名和密码");
            return "error";
        } else {
            session.setAttribute("user", user);
        }
        return "list";//返回list界面
    }


    //查询所有
    @RequestMapping("/SelectUserAll")
    public ModelAndView SelectUserAll(User user, Model model) {
        List<User> list = userService.SelectUserAll();
        ModelAndView mw = new ModelAndView();
        mw.addObject("list", list);
        System.out.println("list====" + list);
        mw.setViewName("getuser");
        return mw;
    }

    /*第三次修改*/
    //删除
    @RequestMapping("/deleteUser")
    public String deleteUser(Long id, Model model) {
        int num = userService.deleteUser(id);
        if ("".equals(num)) {
            model.addAttribute("error", "删除失败");
            return "error";//返回错误界面
        } else {
            return "redirect:/user/SelectUserAll";//删除成功以后，返回剩下所有数据的界面
        }
    }

    //查询修改用户
    @RequestMapping("/editUserId")
    public String editUserId(Long id, Model model) {
        User user = userService.editUserId(id);
        model.addAttribute("user", user);
        return "edit";
    }

    //修改用户
    @RequestMapping("/editUser")
    public String editUser(User user, Model model) {
        int num = userService.editUser(user);
        if (num > 0) {
            return "redirect:/user/SelectUserAll";//编辑成功返回查询所有人界面
        } else {
            model.addAttribute("error", "编辑失败");
            return "error";
        }
    }

    //添加用户
    @RequestMapping("/addUser")
    public String addUser(User user, Model model) {
        int num = userService.addUser(user);
        if (num > 0) {
            return "redirect:/user/SelectUserAll";
        } else {
            model.addAttribute("error", "添加失败");
            return "error";
        }

    }


    //注册
    @RequestMapping("/reg")
    public String reg(User user, Model model) {
        int num = userService.reg(user);
        if (num > 0) {
            return "login";
        } else {
            model.addAttribute("user", user);
            return "error";
        }
    }

    //注销
    @RequestMapping("/logon")
    public String logon(HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println("333" + session);
        session.invalidate();
        return "login";
    }

    //搜索
    @RequestMapping("/find")
    public String find(User user, Model model) {
        List<User> list2 = userService.findinfo(user);
        if ("".equals(list2)) {
            model.addAttribute("error", "请输入正确的用户名");
            return "error";
        } else {
            model.addAttribute("list", list2);
            return "getuser";
        }
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String filename = file.getOriginalFilename();
        System.out.println("filename=====" + filename);
        File dir = new File(path, filename);
        if (!dir.exists()) {
            dir.mkdirs();//目录不存在时，新建目录
        }
        file.transferTo(dir);
        return filename;
    }

    @RequestMapping("/down")
    public void down(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String fileName=request.getSession().getServletContext().getRealPath("upload")+"/101.jpg";
        InputStream bis =new BufferedInputStream(new FileInputStream(new File(fileName)));
        String filename="下载文件.jpg";
        filename=URLEncoder.encode(filename,"UTF-8");
        response.addHeader("Content-Disposition","attachment;filename="+filename);
        response.setContentType("multipart/form-data");
        BufferedOutputStream  out=new BufferedOutputStream (response.getOutputStream());
        int len=0;
        while ((len=bis.read())!=-1){
            out.write(len);
            out.flush();
        }
        out.close();
    }
    //修改密码
    @RequestMapping("/UpdatePwd")
    public String UpdatePwd(User name,String password,String password2,Model model) {

        System.out.println("00000==="+name.getId());
        System.out.println("11111==="+password);
        System.out.println("22222==="+password2);
        if (password .equals(password2)  && password != null && password2 != null) {
            int num = userService.UpdatePwd(name, password, password2);
            if (num > 0) {
                return "login";//编辑成功返回查询所有人界面
            } else {
                model.addAttribute("error", "修改密码失败");
                return null;
            }
        } else {
            model.addAttribute("error", "两次输入密码不一致");
            return "error";
        }
    }


    /**
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/showNewInfo")
    public String showNewInfo(Model model, HttpServletRequest request) {
        //获取当前页数
        String pageNow = request.getParameter("pageNow");
        //获取总页数
        int totalCount=userService.findNewCont();
        Page page=null;
        List<User> list=new ArrayList<User>();
        if(pageNow!=null){
            page=new Page(Integer.valueOf(pageNow),totalCount);
            list=this.userService.findNewsPage(Integer.valueOf(pageNow),page.getPageSize());
        }else{
            page=new Page(1,totalCount);
            list=this.userService.findNewsPage(1,page.getPageSize());
        }
        model.addAttribute("list",list);
        model.addAttribute("page",page);
        return "getuser";
    }
}
